package com.appkubes.mall.admin.application.goods.goods.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.cloud.config.params.paramValid.ParamValid;
import com.appkubes.common.Response;
import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.mall.admin.application.base.BaseController;
import com.appkubes.mall.admin.application.goods.category.service.impl.GoodsCategoryServiceImpl;
import com.appkubes.mall.admin.application.goods.goods.entity.vo.*;
import com.appkubes.mall.admin.application.goods.goods.service.GoodsExtendService;
import com.appkubes.mall.admin.application.goods.goods.service.GoodsService;
import com.appkubes.mall.admin.application.goods.goods.service.impl.GoodsServiceImpl;
import com.appkubes.mall.admin.application.goods.rent.impl.GoodsRentServiceImpl;
import com.appkubes.mall.admin.application.goods.specific.service.GoodsSpecificService;
import com.appkubes.mall.admin.application.goods.specific.service.GoodsSpecificSkuService;
import com.appkubes.mall.core.controller.BaseMallGoodsController;
import com.appkubes.mall.core.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Api(tags = "商品模块")
@RestController
@Slf4j
@RequestMapping({"/sass_admin/Sgoods", "/goods"})
public class GoodsController extends BaseMallGoodsController {
    @Autowired
    GoodsServiceImpl goodsServiceImpl;
    @Autowired
    GoodsCategoryServiceImpl goodsCategoryServiceImpl;
    @Autowired
    GoodsRentServiceImpl goodsRentServiceImpl;
    @Resource
    GoodsExtendService goodsExtendService;
    @Resource
    GoodsService goodsService;
    @Resource
    GoodsSpecificService goodsSpecificService;
    @Resource
    GoodsSpecificSkuService goodsSpecificSkuService;

    @ApiOperation(value = "商品列表")
    @PostMapping("/getList")
    public Response getList(@ParamValid GoodsSearchVO goodsSearchVO) {
        QueryWrapper<MallGoods> queryWrapper = new QueryWrapper<>();
        if ("ASC".equals(goodsSearchVO.getOrderType())) {
            queryWrapper.orderByAsc(goodsSearchVO.getColumn());
        } else {
            queryWrapper.orderByDesc(goodsSearchVO.getColumn());
        }
        if (!StringUtils.isEmpty(goodsSearchVO.getKey())) {
            queryWrapper.like("name", goodsSearchVO.getKey());
        }
        if (!StringUtils.isEmpty(goodsSearchVO.getCatKey())) {
            queryWrapper.eq("cat_key", goodsSearchVO.getCatKey());
        }
        if (!StringUtils.isEmpty(goodsSearchVO.getType())) {
            queryWrapper.eq("type", goodsSearchVO.getType());
        }
        MallGoods query = new MallGoods();
        IPage<MallGoods> page = goodsServiceImpl.selectPageByEntity(query, goodsSearchVO);
        return Response.success(this.getBaseMapper().selectPage(page, queryWrapper));
    }

    @ApiOperation(value = "添加商品")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public Response save(@RequestBody @ParamValid GoodsSaveVO goodsSaveVO) {
        Boolean ret = false;

        // goods数据
        GoodsVO goodsVO = goodsSaveVO.getGoodsVo();
        MallGoods goods = new MallGoods();
        BeanUtils.copyProperties(goodsVO, goods);

        GoodsRentVO goodsRentVO = goodsSaveVO.getGoodsRentVo();
        MallGoodsRent rentData = new MallGoodsRent();
        BeanUtils.copyProperties(goodsRentVO, rentData);

        // 基础信息表相关，暂不改动
        String picsArr = goodsSaveVO.getPicsArr(); //轮播图
        String storeKey = goodsSaveVO.getStoreKey();
        String goodType = goodsSaveVO.getGoodType();

        picsArr = picsArr.substring(1, picsArr.length() - 1);
        picsArr = picsArr.replaceAll("\\\"", "");
        String[] pics = picsArr.split(",");
        for (int i = 0; i < pics.length; i++) {
            System.out.println(pics[i]);
        }
        if ("-1".equals(goods.getGoodsKey())) {
            goods.setGoodsKey(null);
        }
        goods.setCheckState(null);
        goods.setCheckTime(null);
        goods.setFailReason(null);
        goods.setIsHot(null);
        goods.setSalesNum(null);
        goods.setState(null);
        goods.setUpdateTime(null);
        goods.setStoreKey(storeKey);
        goods.setCheckState(2);

        goods.setPics(JSON.toJSONString(StringUtils.isEmpty(pics) ? new ArrayList<>() : pics));
        goods.setUpdateTime(DateUtils.getCurrentTimestamp());
        if  (StringUtils.isEmpty(goods.getGoodsKey())) {
            goods.setCreateTime(DateUtils.DateToTimestamp(new Date()));
        }
        ret = goodsServiceImpl.saveOrUpdate(goods);

        // 存储商品扩展信息
        GoodsExtendVO goodsExtendVO = goodsSaveVO.getGoodsExtendVo();

        MallGoodsExtend mallGoodsExtend = goodsExtendService.getById(goods.getGoodsKey());
        if (mallGoodsExtend == null) {
            mallGoodsExtend = new MallGoodsExtend();
        }
        BeanUtils.copyProperties(goodsExtendVO, mallGoodsExtend);
        mallGoodsExtend.setGoodsKey(goods.getGoodsKey());
        mallGoodsExtend.setColorAttributes(JSONObject.toJSONString(goodsSaveVO.getColors()));
        mallGoodsExtend.setCreateTime(DateUtils.getCurrentTimestamp());
        mallGoodsExtend.setUpdateTime(DateUtils.getCurrentTimestamp());
        goodsExtendService.saveOrUpdate(mallGoodsExtend);

        // 存储租赁相关信息
        rentData.setGoodsKey(goods.getGoodsKey());
        if ("RENT".equals(goodType)) {
            rentData.setCostPerPeriod(rentData.getRentMoney().divide(BigDecimal.valueOf(rentData.getPeriods()), 2)
                    .add(rentData.getRentMoney().multiply(BigDecimal.valueOf(0.01).multiply(rentData.getRentInterestRate()))));
            rentData.setAppKey(null);
            goodsRentServiceImpl.saveOrUpdate(rentData);

        }

        // 存储商品sku信息
        MallGoodsSpecific mallGoodsSpecific = goodsSpecificService.getOne(goods.getGoodsKey());
        if (mallGoodsSpecific == null) {
            if (goodsSaveVO.getSku() != null) {
                mallGoodsSpecific = new MallGoodsSpecific();
                mallGoodsSpecific.setGoodsSpecificKey(UUIDUtils.getUUID());
                mallGoodsSpecific.setGoodsKey(goods.getGoodsKey());
                mallGoodsSpecific.setSpecificData(JSONObject.toJSONString(goodsSaveVO.getSku()));
                mallGoodsSpecific.setSpecificDim1(JSONObject.toJSONString(goodsSaveVO.getDim1()));
                mallGoodsSpecific.setSpecifcDim2(JSONObject.toJSONString(goodsSaveVO.getDim2()));
                mallGoodsSpecific.setSpecifcDim3(JSONObject.toJSONString(goodsSaveVO.getDim3()));
                mallGoodsSpecific.setSpecificDim4(JSONObject.toJSONString(goodsSaveVO.getDim4()));
                mallGoodsSpecific.setCreateTime(DateUtils.getCurrentTimestamp());
                mallGoodsSpecific.setAppKey(null);
                goodsSpecificService.save(mallGoodsSpecific);
            }
        } else {
            mallGoodsSpecific.setSpecificData(JSONObject.toJSONString(goodsSaveVO.getSku()));
            mallGoodsSpecific.setSpecificDim1(JSONObject.toJSONString(goodsSaveVO.getDim1()));
            mallGoodsSpecific.setSpecifcDim2(JSONObject.toJSONString(goodsSaveVO.getDim2()));
            mallGoodsSpecific.setSpecifcDim3(JSONObject.toJSONString(goodsSaveVO.getDim3()));
            mallGoodsSpecific.setSpecificDim4(JSONObject.toJSONString(goodsSaveVO.getDim4()));
            mallGoodsSpecific.setUpdateTime(DateUtils.getCurrentTimestamp());
            goodsSpecificService.getDao().updateById(mallGoodsSpecific);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("msg", "保存成功");
        map.put("data", goods);
        return Response.success(map);

    }

    @ApiOperation(value = "修改信息")
    @PostMapping("/edit")
    public Object edit(@RequestParam String goodsKey) {
        MallGoods info = goodsServiceImpl.getById(goodsKey);
        MallGoodsRent rent = goodsRentServiceImpl.getById(goodsKey);
        MallGoodsExtend extend = goodsExtendService.getById(goodsKey);
        MallGoodsSpecific mallGoodsSpecific = goodsSpecificService.getOne(goodsKey);

        List<GoodsSkuVO> goodsSkuVOList = new ArrayList<>();
        List<ColorAttribute> colors = new ArrayList<>();
        if (mallGoodsSpecific != null && !StringUtils.isEmpty(mallGoodsSpecific.getSpecificData())) {
            goodsSkuVOList = JSONObject.parseArray(mallGoodsSpecific.getSpecificData(), GoodsSkuVO.class);
        }
        if (extend != null && !StringUtils.isEmpty(extend.getColorAttributes())) {
            colors = JSONObject.parseArray(extend.getColorAttributes(), ColorAttribute.class);
        }

        List<MallGoodsCategory> groupList = goodsCategoryServiceImpl.getByState(1);
        Map<String, Object> map = new HashMap<>();
        map.put("info", info);
        map.put("group_list", groupList);
        map.put("rent", rent);
        map.put("extend", extend);
        map.put("specific", mallGoodsSpecific);
        map.put("sku", goodsSkuVOList);
        map.put("skuCodeList", goodsSpecificSkuService.getSkuCodes(goodsKey));
        map.put("colors", colors);
        return Response.success(map);
    }

    @ApiOperation(value = "删除商品")
    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public Response delete(@RequestParam List<String> ids) {
        Boolean flag = goodsService.delete(ids);
        return Response.success(flag);
    }

    @ApiOperation("设置商品状态")
    @PostMapping("/setStatus")
    public Response setState(@RequestBody @ParamValid GoodsSetStateVO goodsSetStateVO) {
        //修改条件
        UpdateWrapper<MallGoods> updateWrapper = new UpdateWrapper();
        updateWrapper.in("goods_key", goodsSetStateVO.getGoodsKeys());

        //修改值
        MallGoods mallGoods = new MallGoods();
        mallGoods.setState(goodsSetStateVO.getState());

        Boolean flag = goodsService.update(mallGoods, updateWrapper);
        return Response.success(flag);
    }

}
